<#
    ReturnCode String  0表示成功, 其他表示失败
    Output     String  JSON, 成功时返回输出内容, 失败时返回错误信息
#>
$Result = @{
    ReturnCode = ""
    Output = ""
}

# 存储会话
$Session = $null

# 与Exchange建立连接
function NewConnection {
    param (
        [string]$User_Name,
        [string]$User_Pwd,
        [string]$PSSession_Name
    )

    [string]$exchangeFilter = "Name='Microsoft Exchange Server'"

    # 检查已安装的应用程序列表中是否存在Exchange Server
    # Check Exchange Server is present in the installed applications list
    $isExchangeExist = Get-CimInstance -ClassName win32_Product -Filter $exchangeFilter | Select Name,Version
    if (!$? -or ([String]::IsNullOrEmpty($isExchangeExist)))  {
        $Script:Result["ReturnCode"] = "0x5E025E27"
        $Script:Result["Output"] = "Exchange"
        return $False
    }

    $ExchangeHost = hostname
    $Password = ConvertTo-SecureString -String $User_Pwd -AsPlainText -Force
    $Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User_Name, $Password
    $Script:Session = New-PSSession -Name $PSSession_Name -ConfigurationName Microsoft.Exchange -ConnectionUri http://$ExchangeHost/PowerShell/ -Authentication Kerberos -Credential $Credentials

    # 检查pssession状态是否可用
    $checkSession = Get-PSSession | Where-Object { $_.Name -eq $pssession_name }
    if ($checkSession.Availability -ne "Available") {
        ClosePSSession $pssession_name
        $Script:Result["ReturnCode"] = "0x64032C10"
        $Script:Result["Output"] = "PSSession status is not used"
        return $False
    }
    return $True
}

# 关闭连接的PSSession
function ClosePSSession {
    param($sessionName)
    Remove-PSSession -Name $sessionName -Confirm:$false -ErrorAction SilentlyContinue
}

function ErrorHandling {
    param($errString)
    $errResult = [PSCustomObject]@{
        message = $errString
        } | ConvertTo-Json -Compress
    $errResult
}
